package com.Cfeng.XiaohuanChat.service.impl;

import com.Cfeng.XiaohuanChat.domain.FileStoreProperties;
import com.Cfeng.XiaohuanChat.service.FileStoreService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * @author Cfeng
 * @date 2022/8/9
 */

@Service
public class FileStoreServiceImpl implements FileStoreService {

    private final Path fileStorgeLocation;


    /**
     * 构造方法，引入配置的路径对象，直接写在参数中，spring自动将容器中的对象注入
     */
    public FileStoreServiceImpl(FileStoreProperties fileStoreProperties) throws IOException {
        //绝对路径赋值
        this.fileStorgeLocation = Paths.get(fileStoreProperties.getUploadDir()).toAbsolutePath().normalize();
        //利用files创建文件夹
        Files.createDirectories(this.fileStorgeLocation);
    }


    @Override
    public String uploadFile(MultipartFile multipartFile) {
        //文件名称
        String originalName = multipartFile.getOriginalFilename();
        //文件的扩展名,就是.之后的部分，如果找不到.或者文件名为null，那就没有扩展名
        String extName = (originalName == null || originalName.lastIndexOf(".") <= 0) ? null : originalName.substring(originalName.lastIndexOf("."));

        //使用UUID进行加密
//        String prefixName = (originalName == null || originalName.lastIndexOf(".") <= 0) ? null : originalName.substring(0,originalName.lastIndexOf("."));
//        String codeName = new String(Base64Utils.encode(prefixName.getBytes(Charset.forName("utf-8"))));
//        替换特殊字符,string为final类，产生的为新的,4个反斜杠表示一个反斜杠
//        String newCode =  codeName.replaceAll(".","1").replaceAll("/","2").replaceAll("\\\\","3").replaceAll("=","4");

        String fileName = UUID.randomUUID().toString().replace("-","") + extName;
        //文件名中不能有两个..
        if(fileName.contains("..")) {
            throw new RuntimeException("Sorry,FileName contains invalid path sequence" + fileName);
        }
        //根据文件名获取到最终的Path对象,将fileName拼接在最后面
        Path target = fileStorgeLocation.resolve(fileName);

        try{
            //将上传的文件转为IO流复制到target路径文件,选项为操作的行为
            Files.copy(multipartFile.getInputStream(),target, StandardCopyOption.REPLACE_EXISTING);
        }catch (IOException e) {
            throw new RuntimeException("Could not store file" + fileName + "please try again !", e);
        }
        return fileName;
    }

    @Override
    public Resource loadFile(String fileName) throws FileNotFoundException {
        //首先获得完整的文件路径
        Path filePath = fileStorgeLocation.resolve(fileName).normalize();
        //使用UrlResource将这个路径的资源获取
        try {
            Resource resource  = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            }else {
                //不存在抛异常
                throw new FileNotFoundException("file not found" + fileName);
            }
        } catch (MalformedURLException e) {
            throw new FileNotFoundException(("file not found" + fileName));
        }
    }
}
